const websocket = require('ws')

const ws = new websocket.Server({//创建端口8000的服务
    port: 8000
})

let clients = {}
let clientNum = 0

ws.on('connection', (client) => { 
    //  监听连接客户端
    //给每个链接的客户端起个名字
    client.name = ++clientNum
    clients[client.name] = client       //创建键值对 ‘1’：client实例

    //用client监听四个常用事件 open message close error
    //监听客户端message事件，拿到客户端发送来的消息
    client.on('message', (msg) => {
    console.log('用户'+client.name+'说：'+msg)
    broadcast(client,msg)
    })

        //监听客户端error事件，拿到客户端发送来错误
   client.on("error",(err)=>{//监听客户端错误事件
        if(err){
            console.log(err);  
        }
    })
    //监听客户端close事件，下线事件
   client.on("close",()=>{//监听客户端错误事件
        broadcastQuite(client)
        console.log("用户"+client.name+"下线了！");
        delete clients[client.name] // 从容器中删除下线的客户端实例
    })

        
    function broadcast(client,msg) {
        for (let key in clients) {
            clients[key].send('用户'+client.name+'说：'+msg)
        }
    }



//广播下线
    function broadcastQuite  (client) {
        for (let key in clients) {
            clients[key].send('系统提示：用户'+client.name+'下线了')
        }
    }
})